package io.renren.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import io.renren.common.exception.RRException;
import io.renren.common.utils.Constant;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.entity.SeatApplicationEntity;
import io.renren.entity.SeatEslEntity;
import io.renren.param.SeatApplicationSaveParam;
import io.renren.service.EslContentService;
import io.renren.service.SeatApplicationService;
import io.renren.service.SeatEslService;
import io.renren.service.SeatService;
import io.renren.vo.SeatVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 工位申请记录
 *
 * @author 1
 * @email 1@2.com
 * @date 2021-11-19 11:03:23
 */
@RestController
@RequestMapping("/seatapplication")
@Slf4j
public class SeatApplicationController {

    @Autowired
    private SeatApplicationService seatApplicationService;
    @Autowired
    private SeatService seatService;
    @Autowired
    private EslContentService eslContentService;
    @Autowired
    private SeatEslService seatEslService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
//        List<SeatApplicationVo> vos = new ArrayList<>();
//        PageUtils page = new PageUtils(vos, 0, 10, 1);
//
//
//        SeatPageUtils pageUtils = seatService.queryPage(params);
//        List<SeatVo> seatEntities = (List<SeatVo>) pageUtils.getShareList();
//        if (CollectionUtil.isNotEmpty(seatEntities)) {
//            List<Long> ids = new ArrayList<>();
//            for (SeatVo seatEntity : seatEntities) {
//                ids.add(seatEntity.getId());
//            }
//            params.put("seatIds", ids);
//            page = seatApplicationService.queryPage(params);
//        }

        PageUtils page = seatApplicationService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        SeatApplicationEntity seatApplication = seatApplicationService.getById(id);

        return R.ok().put("seatApplication", seatApplication);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @Transactional
    public R save(@RequestBody SeatApplicationSaveParam param) {
        if (DateUtil.compare(param.getStartTime(), new Date()) < 0) {
            log.error("开始时间{}不能小于当前时间", param.getStartTime());
            throw new RRException("开始时间不能小于当前时间");
        }

        SeatVo seatVo = seatService.queryByCodeAndCompId(param.getSeatCode(), param.getCompId());
        if (seatVo == null || seatVo.getId() == null) {
            log.error("根据编号{}查不到工位", param.getSeatCode());
            return R.error("根据编号查不到工位");
        }

        SeatEslEntity seatEslEntity = seatEslService.queryBySeatId(seatVo.getId());
        if (seatEslEntity == null || seatEslEntity.getEslId() == null) {
            throw new RRException("工位" + seatVo.getCode() + "未绑定铭牌，不能预定");
        }

        SeatApplicationEntity seatApplication = SeatApplicationEntity.convertFor(param);

        List<SeatApplicationEntity> applicationEntities = seatApplicationService.queryUnfinish(seatVo.getId());
        for (SeatApplicationEntity applicationEntity : applicationEntities) {
            if (DateUtil.compare(param.getStartTime(), applicationEntity.getStartTime()) > 0
                    && DateUtil.compare(param.getStartTime(), applicationEntity.getEndTime()) < 0 //预约的开始时间在 已约记录的时间段内
                    ||
                    DateUtil.compare(param.getEndTime(), applicationEntity.getStartTime()) > 0
                            && DateUtil.compare(param.getEndTime(), applicationEntity.getEndTime()) < 0 //预约的结束时间在 已约记录的时间段内
                    ||
                    DateUtil.compare(applicationEntity.getStartTime(), param.getStartTime()) > 0
                            && DateUtil.compare(applicationEntity.getStartTime(), param.getEndTime()) < 0 //已约记录的开始时间在 预约的时间段内
                    ||
                    DateUtil.compare(applicationEntity.getEndTime(), param.getStartTime()) > 0
                            && DateUtil.compare(applicationEntity.getEndTime(), param.getEndTime()) < 0 //已约记录的结束时间在 预约的时间段内
            ) {
                log.error("工位编号{}在{} ~ {}内已有预定", seatVo.getCode(), DateUtil.format(param.getStartTime(), DatePattern.NORM_DATETIME_FORMAT), DateUtil.format(param.getEndTime(), DatePattern.NORM_DATETIME_FORMAT));
                return R.error("该时间段已被预定");
            }
        }

        seatApplication.setSeatId(seatVo.getId());
        seatApplicationService.save(seatApplication);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @Transactional
    public R update(@RequestBody SeatApplicationEntity seatApplication) {
        ValidatorUtils.validateEntity(seatApplication);

        SeatApplicationEntity applicationEntity = seatApplicationService.getById(seatApplication.getId());
        if (Constant.ApplicationState.STARTED.getValue().equals(applicationEntity.getState())) {
            SeatEslEntity seatEslEntity = seatEslService.queryBySeatId(applicationEntity.getSeatId());
            //刷新铭牌
            applicationEntity.setState(seatApplication.getState());
            eslContentService.refreshSeatPlate(applicationEntity, seatEslEntity);
        }

        seatApplicationService.updateById(seatApplication);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @Transactional
    public R delete(@RequestBody Long[] ids) {

        for (Long id : ids) {
            //清空铭牌内容
            SeatApplicationEntity seatApplicationEntity = seatApplicationService.getById(id);
            if (!Constant.ApplicationState.APPLIED.getValue().equals(seatApplicationEntity.getState())) {
                throw new RRException("状态为未开始才能取消");
            }
        }

        seatApplicationService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
